//
// Created by 原帅 on 2022/11/5.
//

#include "RProcessor.h"
#include "RLog.h"
#include "unistd.h"
#include "algorithm"

int RProcessor::process() {
    if (processors.empty())
    {
        if (nothingTodoLogFlag)
        {
            RLogErr("processors vector is empty! nothing to do!");
            nothingTodoLogFlag = false;
//            return -1;
        }
        usleep(this->nothingTodoUSleepCount);
    }
    else
    {
        nothingTodoLogFlag = true;
        for (auto proc:processors)
        {
            if (proc == nullptr)
            {
                RLogErr("an interface is nullptr in processor vector,auto remove it")
                this->processors.erase(std::find(processors.begin(),processors.end(),proc));
                continue;
            }
            int iRet = proc->process();
            if (iRet) {
                iRet = proc->fail(iRet);
                if (iRet) return iRet;
            }
        }
    }
    return 0;
}

int RProcessor::registerProc(RProcIF *rProcIf) {
    if (std::find(processors.begin(),processors.end(),rProcIf)==processors.end())
    {
        processors.push_back(rProcIf);
    }
    else
    {
        RLogErr("there is a same interface already in process vector");
        return -1;
    }
    return 0;
}

long RProcessor::getNothingTodoUSleepUsec() const {
    return nothingTodoUSleepCount;
}

void RProcessor::setNothingTodoUSleepUSec(long usec) {
    RProcessor::nothingTodoUSleepCount = usec;
}
